<template>
    <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
    <div class="container">

        <TableCustom 
            :columns="columns" 
            :tableData="tableData" 
            :pageSize="page.limit"  
            :total="page.total"
            :getPageSize="handlePageSizeChange" 
            :delsFunc="delSelection" 
            :page-change="changePage" 
            :editFunc="handleEdit"
        >
            <!-- 表格上面的按钮 -->
            <template #toolbarBtn>
                <el-button type="warning" :icon="CirclePlusFilled" @click="showAdd = true">新增</el-button>
            </template>
            <template #operation="{ row, index }">
                 <el-button type="warning"  @click="handleEdit(row)">查看</el-button>
                 <el-button type="primary"  @click="handleEdit(row)">编辑</el-button>
                 <el-button type="danger"  @click="handleDelete(row)">删除</el-button>
            </template>
        </TableCustom>
    </div>
    <!-- 添加弹窗 -->
    <KdDialog 
        v-model="showAdd" 
        title="添加装备"
        width="900px"
    >
        <Equip :openType="'add'"/>
        <template #footer>
            <el-button type="primary" @click="">确定</el-button>
            <el-button @click="showAdd = false">取消</el-button>
        </template>
    </KdDialog>
</template>

<script setup lang="ts" name="system-role">
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { Role } from '@/types/role';
import TableCustom from '@/components/table-custom.vue';
import Equip from './components/equip.vue';
import KdDialog from '@/components/kd-dialog.vue';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import { FormOptionList } from '@/types/form-option';
import {ajax } from '@/api';
/************************* 控制变量 *******************************/
const tableData = ref<any[]>([]);

// 查询相关
const query = reactive({
    name: '',
    status: '0'
});
const searchOpt = ref<FormOptionList[]>([
    { type: 'input', label: '角色名称：', prop: 'name' }
])

const page = reactive({
    index: 1,
    limit: 10, // 每页显示条数，默认10条
    total: 0,
    isPage: true, // 是否分页，默认为true
    paramList: [] // 分页参数列表
})
// 显示 “添加” 弹窗
const showAdd = ref(false);

const permissOptions = ref({})

const isEdit = ref(false);
const rowData = ref({});

/************************* 配置 *******************************/

// 表格相关
let columns = ref([
    { type: 'index', label: '序号', width: 55, align: 'center' },
    { prop: 'name', label: '角色名称' },
    { prop: 'roleKey', label: '角色标识' },
    { prop: 'status', label: '状态' },
    { prop: 'permissions', label: '权限管理' },
    { prop: 'operation',  width: 250,label: '操作'},
])


/************************* 点击触发 *******************************/

//设置搜索参数
const setSearchParam = () => {
    page.paramList = [];
    Object.entries(query).forEach(([key, value]) => {
        if (key == "status") {
            page.paramList.push({
                paramName: key,
                paramValue: value,
                paramType: 'eq'
            });
        }
        else if (value) { // 确保值不为空
            page.paramList.push({
                paramName: key,
                paramValue: value,
                paramType: 'eq'
            });
        }
    });
}

// 更新数据插入数据
const updateData = (data: any) => {
    console.log("是否为编辑:"+isEdit);
    if( !isEdit.value ){
       addDataApi(data);
    }
    else{
       updateDataApi(data);
    }
};


// 搜索函数：触发分页重置到第一页
const handleSearch = () => {
    changePage(1); // 调用分页函数，切换到第一页
};


// 编辑
const handleEdit = (row: Role) => {
    console.log("编辑:"+JSON.stringify(row));
    rowData.value = { ...row };
    isEdit.value = true;
};
// 关闭弹窗
const closeDialog = () => {
    isEdit.value = false;
    rowData.value = {};
};
/*************************  表格的封装方法 *******************************/
// 分页
const changePage = (val: number) => {
    page.index = val;
    getDataApi();
};

// 删除相关
const handleDelete = (data: Role) => {
    let ids = [data.id];
    deleteDataApi(ids);
}
//切换每页条数
const handlePageSizeChange = (val: number) => {
    page.limit = val; // 更新每页条数
    page.index = 1;
    getDataApi();
};

// 删除选中的项目
const delSelection = (data: any[]) => {
    console.log(JSON.stringify(data));
    let obj = {
        ids: [],
    };
    let ids = [];
    data.forEach((item: any) => {
        ids.push(item.id);
    });
    obj.ids = ids;
    deleteDataApi(obj);
};
/*************************  Api请求  *******************************/
// 从后端接口获取用户数据
const getDataApi = async () => {
    setSearchParam();
    ajax({
        url: "role/list",
        method: 'POST', // 修正参数名称
        data: page,
        success: (res) => {
            if( res.code == 0){
                if( page.isPage == true ){
                    tableData.value = res.data.records;
                    page.total = res.data.total; // 更新总记录数
                }else{
                    tableData.value = res.data;
                    page.total = res.data.length;
                }
            }else{
                ElMessage.error(res.msg);
            }
        }
    });

};

//添加数据
const addDataApi = async (data: any) => {
    ajax({
        url: "role/add",
        method: 'POST', // 修正参数名称
        data: data,
        success: (res) => {
            if( res.code == 0){
                ElMessage.success(res.msg);
                closeDialog(); 
                getDataApi(); 
            }else{
                ElMessage.error(res.msg);
            }
        }
    });
};

//修改数据
const updateDataApi = async (data: any) => {
    ajax({
        url: "role/update",
        method: 'POST', // 修正参数名称
        data: data,
        success: (res) => {
            if( res.code == 0){
                ElMessage.success(res.msg);
                closeDialog(); // 关闭弹窗
                getDataApi(); // 重新获取数据
            }else{
                ElMessage.error(res.msg);
            }
        }
    });
};

//删除数据
const deleteDataApi = async (data: any) => {
    ajax({
        url: "role/delete",
        method: 'POST', // 修正参数名称
        data: {ids:data},
        success: (res) => {
            if( res.code == 0){
                ElMessage.success(res.msg);
                closeDialog(); // 关闭弹窗
                getDataApi(); // 重新获取数据
            }else{
                ElMessage.error(res.msg);
            }
        }
    });
};
getDataApi();
</script>

<style scoped></style>